package com.itheima.health.security;

import com.itheima.health.common.MessageConst;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@Aspect
@Component
@Slf4j
public class SecurityAdvisor {

    /*@Before("test()&&@annotation(security)")
    public Result permissionControl( Security security) {
        //请求Url所需要的权限
        String needPermission = security.value();
        //当前用户的信息
        SecurityUser securityUser = SecurityContext.getSecurityUserThreadLocal();
        log.info("[权限控制]-用户:{}-所需权限:{}",securityUser.getUsername(),needPermission);
        Set<Role> roles = securityUser.getRoles();
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                if (permission.getKeyword().equals(needPermission)) {
                    log.info("[权限控制]-权限检查通过");
                }
            }
        }
        log.info("[权限控制]-权限不足");
        return new Result(false,"权限不足");
    }*/

    @Around("@annotation(com.itheima.health.security.Security)")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        System.out.println("---------权限控制------------");
        Security security = ((MethodSignature) point.getSignature()).getMethod().getAnnotation(Security.class);
        String needPermission = security.value();
        log.info("[权限检查]-需要权限:{}",needPermission);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        SecurityUser securityUser = (SecurityUser) request.getSession().getAttribute(MessageConst.CURRENT_USER);
        //SecurityUser securityUser = SecurityContext.getSecurityUserThreadLocal();
        log.info("[权限控制]-用户:{}-访问路径:{}-所需权限:{}",securityUser.getUsername(),request.getRequestURI(),needPermission);
        Set<Role> roles = securityUser.getRoles();
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                if (permission.getKeyword().equals(needPermission)) {
                    log.info("[权限控制]-权限检查通过");
                    return point.proceed(point.getArgs());
                }
            }
        }
        throw new BusinessRuntimeException("权限不足");
    }
}
